package cloud.tianai.ram.policy.client;

import cloud.tianai.ram.policy.common.model.dto.Statement;
import cloud.tianai.ram.policy.common.model.dto.Match;
import cloud.tianai.ram.policy.common.model.dto.Action;
import org.springframework.core.NamedThreadLocal;

import java.util.List;

/**
 * @Author: 天爱有情
 * @date 2022/3/23 15:51
 * @Description RamContext
 */
public class RamContext {

    private static final ThreadLocal<Action> CURRENT_ACTION = new NamedThreadLocal<>("Current Action");
    private static final ThreadLocal<Match> CURRENT_MATCH = new NamedThreadLocal<>("Current Match");
    private static final ThreadLocal<List<Statement>> CURRENT_STATEMENT = new NamedThreadLocal<>("Current Statement");

    public static Action currentAction() throws IllegalStateException {
        Action action = CURRENT_ACTION.get();
        if (action == null) {
            throw new IllegalStateException("Cannot find current Action");
        }
        return action;
    }

    public static Object setCurrentAction(Action action) {
        Action old = CURRENT_ACTION.get();
        if (action != null) {
            CURRENT_ACTION.set(action);
        } else {
            CURRENT_ACTION.remove();
        }
        return old;
    }


    public static Match currentMatch() throws IllegalStateException {
        Match match = CURRENT_MATCH.get();
        if (match == null) {
            throw new IllegalStateException("Cannot find current Match");
        }
        return match;
    }

    public static Match setCurrentMatch(Match match) {
        Match old = CURRENT_MATCH.get();
        if (match != null) {
            CURRENT_MATCH.set(match);
        } else {
            CURRENT_MATCH.remove();
        }
        return old;
    }


    public static List<Statement> currentStatement() throws IllegalStateException {
        List<Statement> statementList = CURRENT_STATEMENT.get();
        if (statementList == null) {
            throw new IllegalStateException("Cannot find current statement");
        }
        return statementList;
    }

    public static List<Statement> setCurrentStatement(List<Statement> statementList) {
        List<Statement> old = CURRENT_STATEMENT.get();
        if (statementList != null) {
            CURRENT_STATEMENT.set(statementList);
        } else {
            CURRENT_STATEMENT.remove();
        }
        return old;
    }
}
